package advanced.network.basic_servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义
 * 处理web的上下文,  处理和解析相应的反射信息
 */
public class WebContext {
    private List<Entity> entities;
    private List<Mapping> mappings;
    // map 的key是servlet-name value=servlet-class
    private Map<String, String> entityMap = new HashMap<>();
    //key --> url-pattern value--> servlet-class 因为一个servlet-name 可能对应了多个url-pattern
    private Map<String, String> mappingMap = new HashMap<>();

    public WebContext(List<Entity> entities, List<Mapping> mappings) {
        this.entities = entities;
        this.mappings = mappings;
        for (Entity entity : entities) {
            //将entity的list转换成对应的map
            entityMap.put(entity.getName(), entity.getClz());
        }
        //将map的list专窗对应的map
        for (Mapping mapping : mappings) {
            for (String pattern : mapping.getPatterns()) {
                mappingMap.put(pattern, mapping.getName());
            }
        }
    }

    /**
     * 获取反射的类名
     *
     * @param pattern
     * @return
     */
    public String getClz(String pattern) {
        String name = mappingMap.get(pattern);

        return entityMap.get(name);
    }
}
